package com.red.service.impl;

import cn.hutool.core.lang.UUID;
import com.red.dao.GoodsRepository;
import com.red.dao.GoodsSellRepository;
import com.red.dao.OrdersRepository;
import com.red.dao.UserRepository;
import com.red.entity.Goods;
import com.red.entity.GoodsSell;
import com.red.entity.Orders;
import com.red.entity.User;
import com.red.redisDo.OrderRedisDo;
import com.red.service.OrderRedisService;
import com.red.service.OrderService;
import com.red.vo.PayOrderRequestVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.Optional;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2021-09-23 12:02
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrdersRepository payOrderRepository;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private GoodsSellRepository goodsSellsRepository;

    @Autowired
    private OrderRedisService orderRedisService;

    @Override
    @Transactional
    public String payOrder(PayOrderRequestVo requestVo) {
        //模拟生成订单号  （由支付宝或者微信生成）
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        //保存订单信息
        Orders order = new Orders();
        order.setCreateTime(new Date());
        order.setChannel(requestVo.getChannel());
        order.setPayAmount(requestVo.getCount());
        order.setTradeNo(tradeNo);
        order.setStatus(0);
        payOrderRepository.save(order);
        //保存商品支付信息
        GoodsSell goodsSell = new GoodsSell();
        goodsSell.setCount(requestVo.getCount());
        goodsSell.setStatus(0);
        goodsSell.setOrder(order);
        //查询用户信息，关联商品销售
        User user = userRepository.findById(requestVo.getUserId()).get();
        goodsSell.setUser(user);
        //查询商品信息，关联商品销售
        Goods goods = goodsRepository.findById(requestVo.getGoodsId()).get();
        goodsSell.setGoods(goods);
        goodsSellsRepository.save(goodsSell);
        //信息存入redis的对象
        OrderRedisDo orderRedisDo = new OrderRedisDo();
        //复制部分属性
        BeanUtils.copyProperties(order,orderRedisDo);
        orderRedisDo.setGoodsId(requestVo.getGoodsId());
        //保存信息
        orderRedisService.saveOrder(tradeNo, orderRedisDo);
        return tradeNo;
    }
}
